{% extends "base.html" %}

{% block title %}用户行为分析 - 妙趣拾光锦盒管理系统{% endblock %}

{% block head %}
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.0/echarts.min.js"></script>
<style>
.chart-container {
    height: 350px;
    margin-bottom: 20px;
}

.data-card {
    transition: all 0.3s;
}

.data-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}

.metric-value {
    font-size: 1.8rem;
    font-weight: bold;
}

.metric-label {
    font-size: 0.9rem;
    color: #6c757d;
}

.time-filter {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 1rem;
}

.time-filter .btn-group .btn {
    border-radius: 20px;
    font-size: 0.8rem;
    padding: 0.25rem 0.75rem;
}

.table th, .table td {
    vertical-align: middle;
}

.page-header {
    border-left: 5px solid #007bff;
    padding-left: 1rem;
    margin-bottom: 1.5rem;
}

.breadcrumb {
    background-color: transparent;
    padding: 0;
    margin-bottom: 1rem;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{{ url_for('main.index') }}">首页</a></li>
            <li class="breadcrumb-item"><a href="{{ url_for('analytics.dashboard') }}">数据分析</a></li>
            <li class="breadcrumb-item active" aria-current="page">用户行为分析</li>
        </ol>
    </nav>

    <div class="row mb-4">
        <div class="col-12 d-flex justify-content-between align-items-center">
            <h2 class="mb-0"><i class="fas fa-chart-line me-2"></i>用户行为分析</h2>
        </div>
    </div>

    <!-- 用户行为趋势分析 -->
    <div class="card shadow-sm">
        <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-chart-area me-2"></i>用户行为趋势</h5>
            <div class="btn-group">
                <button type="button" class="btn btn-primary" data-range="7">最近7天</button>
                <button type="button" class="btn btn-outline-primary" data-range="14">最近14天</button>
                <button type="button" class="btn btn-outline-primary" data-range="30">最近30天</button>
            </div>
        </div>
        <div class="card-body">
            <div id="behaviorChart" style="height: 400px;"></div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-lg-6">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">转化漏斗分析</h5>
                </div>
                <div class="card-body">
                    <div id="funnel-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">用户行为分布</h5>
                </div>
                <div class="card-body">
                    <div id="behavior-pie-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0">热门页面分析</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>页面URL</th>
                                    <th>访问次数</th>
                                    <th>独立访客</th>
                                    <th>人均访问</th>
                                </tr>
                            </thead>
                            <tbody id="popular-pages">
                                <tr>
                                    <td colspan="4" class="text-center">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-header bg-warning text-white">
                    <h5 class="mb-0">热门搜索词</h5>
                </div>
                <div class="card-body">
                    <div id="search-keywords-chart" class="chart-container"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化ECharts图表
    const chart = echarts.init(document.getElementById('behaviorChart'));
    const funnelChart = echarts.init(document.getElementById('funnel-chart'));
    const pieChart = echarts.init(document.getElementById('behavior-pie-chart'));
    const keywordsChart = echarts.init(document.getElementById('search-keywords-chart'));
    
    let currentRange = 7; // 默认显示最近7天
    
    // 根据日期范围更新图表
    function updateChart(days) {
        // 显示加载动画
        chart.showLoading();
        
        // 发送AJAX请求获取数据
        fetch(`/analytics/api/analytics/user_behavior?days=${days}`)
            .then(response => response.json())
            .then(data => {
                // 隐藏加载动画
                chart.hideLoading();
                
                // 配置图表选项
                const option = {
                    title: {
                        text: '用户行为趋势分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        }
                    },
                    legend: {
                        data: ['加入购物车', '聊天', '表单提交', '页面浏览', '查看商品', '查看超市', '查看订单'],
                        bottom: 0
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '10%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: data.dates
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '加入购物车',
                            type: 'line',
                            data: data.cart_adds
                        },
                        {
                            name: '聊天',
                            type: 'line',
                            data: data.chats
                        },
                        {
                            name: '表单提交',
                            type: 'line',
                            data: data.form_submits
                        },
                        {
                            name: '页面浏览',
                            type: 'line',
                            data: data.page_views
                        },
                        {
                            name: '查看商品',
                            type: 'line',
                            data: data.product_views
                        },
                        {
                            name: '查看超市',
                            type: 'line',
                            data: data.market_views
                        },
                        {
                            name: '查看订单',
                            type: 'line',
                            data: data.order_views
                        }
                    ]
                };
                
                // 设置图表
                chart.setOption(option);
            })
            .catch(error => {
                console.error('获取数据失败:', error);
                chart.hideLoading();
            });
    }
    
    // 更新转化漏斗图表
    function updateFunnelChart() {
        funnelChart.showLoading();
        
        fetch('/analytics/api/funnel_analysis')
            .then(response => response.json())
            .then(data => {
                funnelChart.hideLoading();
                
                const option = {
                    title: {
                        text: '用户转化漏斗',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b} : {c} ({d}%)'
                    },
                    legend: {
                        data: data.stages,
                        bottom: 0
                    },
                    series: [
                        {
                            name: '转化阶段',
                            type: 'funnel',
                            left: '10%',
                            top: 60,
                            bottom: 60,
                            width: '80%',
                            min: 0,
                            max: data.values[0],
                            minSize: '0%',
                            maxSize: '100%',
                            sort: 'descending',
                            gap: 2,
                            label: {
                                show: true,
                                position: 'inside'
                            },
                            labelLine: {
                                length: 10,
                                lineStyle: {
                                    width: 1,
                                    type: 'solid'
                                }
                            },
                            itemStyle: {
                                borderColor: '#fff',
                                borderWidth: 1
                            },
                            emphasis: {
                                label: {
                                    fontSize: 20
                                }
                            },
                            data: data.stages.map((stage, index) => {
                                return {
                                    value: data.values[index],
                                    name: stage + ' (' + data.conversion_rates[index] + '%)'
                                };
                            })
                        }
                    ]
                };
                
                funnelChart.setOption(option);
            })
            .catch(error => {
                console.error('获取漏斗数据失败:', error);
                funnelChart.hideLoading();
            });
    }
    
    // 更新用户行为分布饼图
    function updateBehaviorPieChart() {
        pieChart.showLoading();
        
        fetch('/analytics/api/user_behavior')
            .then(response => response.json())
            .then(data => {
                pieChart.hideLoading();
                
                // 定义行为类型的中文映射
                const behaviorNames = {
                    'page_view': '页面浏览',
                    'view_box': '查看商品',
                    'view_market': '查看超市',
                    'view_order': '查看订单',
                    'add_to_cart': '加入购物车',
                    'add_cart': '加入购物车',
                    'form_submit': '表单提交',
                    'chat': '聊天',
                    'search': '搜索',
                    'purchase': '购买',
                    'browse': '浏览',
                    'view': '查看'
                };
                
                const option = {
                    title: {
                        text: '用户行为分布',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b} : {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        data: data.map(item => behaviorNames[item.behavior_type] || item.behavior_type)
                    },
                    series: [
                        {
                            name: '行为类型',
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: data.map(item => {
                                return {
                                    value: item.count,
                                    name: behaviorNames[item.behavior_type] || item.behavior_type
                                };
                            }),
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                
                pieChart.setOption(option);
            })
            .catch(error => {
                console.error('获取行为分布数据失败:', error);
                pieChart.hideLoading();
            });
    }
    
    // 更新热门页面表格
    function updatePopularPages() {
        const tableBody = document.getElementById('popular-pages');
        tableBody.innerHTML = `
            <tr>
                <td colspan="4" class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </td>
            </tr>
        `;
        
        fetch('/analytics/api/popular_pages')
            .then(response => response.json())
            .then(data => {
                let html = '';
                
                if (data.length === 0) {
                    html = `
                        <tr>
                            <td colspan="4" class="text-center">暂无数据</td>
                        </tr>
                    `;
                } else {
                    data.forEach(page => {
                        html += `
                            <tr>
                                <td>${page.url}</td>
                                <td>${page.visit_count}</td>
                                <td>${page.unique_users}</td>
                                <td>${page.avg_visits_per_user}</td>
                            </tr>
                        `;
                    });
                }
                
                tableBody.innerHTML = html;
            })
            .catch(error => {
                console.error('获取热门页面数据失败:', error);
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="4" class="text-center text-danger">加载失败</td>
                    </tr>
                `;
            });
    }
    
    // 更新热门搜索词图表
    function updateSearchKeywords() {
        keywordsChart.showLoading();
        
        fetch('/analytics/api/search_keywords')
            .then(response => response.json())
            .then(data => {
                keywordsChart.hideLoading();
                
                // 限制显示前10个关键词
                const topKeywords = data.slice(0, 10);
                
                const option = {
                    title: {
                        text: '热门搜索词',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value'
                    },
                    yAxis: {
                        type: 'category',
                        data: topKeywords.map(item => item.keyword),
                        axisTick: {
                            alignWithLabel: true
                        }
                    },
                    series: [
                        {
                            name: '搜索次数',
                            type: 'bar',
                            data: topKeywords.map(item => item.count)
                        }
                    ]
                };
                
                keywordsChart.setOption(option);
            })
            .catch(error => {
                console.error('获取搜索词数据失败:', error);
                keywordsChart.hideLoading();
            });
    }

    // 监听时间范围按钮点击
    document.querySelectorAll('.btn-group button').forEach(button => {
        button.addEventListener('click', function() {
            const days = parseInt(this.dataset.range);
            
            // 更新按钮样式
            document.querySelectorAll('.btn-group button').forEach(btn => {
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-primary');
            });
            this.classList.remove('btn-outline-primary');
            this.classList.add('btn-primary');
            
            // 更新图表
            currentRange = days;
            updateChart(days);
        });
    });

    // 初始化所有图表
    updateChart(currentRange);
    updateFunnelChart();
    updateBehaviorPieChart();
    updatePopularPages();
    updateSearchKeywords();

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', function() {
        chart.resize();
        funnelChart.resize();
        pieChart.resize();
        keywordsChart.resize();
    });
});
</script>
{% endblock %} 